$(function () {

    window.curD = new Date();
    window.localVarTemplate = 'ahoireportchromeplugin-template';
    window.localVarDept = 'ahoireportchromeplugin-dept';
    window.localVarManager = 'ahoireportchromeplugin-manager';

    var dept = [];
    dept.push({id: '801', name: '广深港高铁供电系统（深圳供电段）(TY16026-02-03-20)'});
    dept.push({id: '', name: '...'});
    dept.push({id: '', name: '（配置更多部门请联系插件开发者）'});
    window.localStorage.setItem(localVarDept, JSON.stringify(dept));

    var manager = [];
    manager.push({id: '2', name: '罗旺春'});
    manager.push({id: '71', name: '吴鹏俊'});
    manager.push({id: '', name: '...'});
    manager.push({id: '', name: '（配置更多上级主管请联系插件开发者）'});
    window.localStorage.setItem(localVarManager, JSON.stringify(manager));

    gen(new Date());
    initTemplate();

    // 一键送审
    $('#ss').click(function () {
        var paramT = window.localStorage.getItem(localVarTemplate);
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function (t) {
            chrome.tabs.sendMessage(t[0].id, {
                type: 'list',
                params: JSON.parse(paramT)
            });
        });
    });
    // 一键填报
    $('#data').click(function () {
        $('#template-edit-div ul').hide();
        $('#template-edit-div table').show();
        var clickDay = $('#selected-date').attr('data');
        if (clickDay == '' || clickDay == null) {
            $('#selected-date').css('color', 'red');
            $('#selected-date').animate({
                'font-size': '16px'
            });
            $('#selected-date').animate({
                'font-size': '14px'
            });
            return;
        }

        if (!validForm()) return;

        // 触发保存
        $('#bc').click();

        var paramT = window.localStorage.getItem(localVarTemplate);
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function (t) {
            chrome.tabs.sendMessage(t[0].id, {
                type: 'add',
                workDate: clickDay,
                params: JSON.parse(paramT)
            });
        });
    });
    // 统计加班
    $('#countJB').click(function () {
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function (t) {
            chrome.tabs.sendMessage(t[0].id, {
                type: 'countJB'
            });
        });
    });
    // 一键读邮件
    $('#readMail').click(function () {
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function (t) {
            chrome.tabs.sendMessage(t[0].id, {
                type: 'readMail'
            });
        });
    });
    // 一键读消息
    $('#readMsg').click(function () {
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function (t) {
            chrome.tabs.sendMessage(t[0].id, {
                type: 'readMsg'
            });
        });
    });
    // 替换页标
    $('#repalcePageTitle').click(function () {
        chrome.tabs.query({}, function (t) {
            var html = '<ul style="list-style: none;padding: 0;">';
            $.each(t, function (i, e) {
                html += '<li style="margin-bottom: 10px;white-space: nowrap;">' +
                    '<span style="color: blue;border: 1px solid;padding: 0 2px;cursor: pointer;" class="hide-tab" tabid="' + e.id + '">隐藏</span>' +
                    '<span style="margin-left: 10px;" title="' + e.title + '">' + e.title + '</span>' +
                    '</li>';
            });
            html += '</ul>';
            $('#template-edit-div table').hide();
            $('#template-edit-div ul').remove();
            $('#template-edit-div').append(html).find('ul span.hide-tab').click(function () {
                chrome.tabs.executeScript(parseInt($(this).attr('tabid')), {code: 'document.title=""'}, function () {
                    $('#repalcePageTitle').click();
                });
            });
        });
    });
    // 上个月
    $('#left').click(function () {
        var nd = new Date();
        nd.setFullYear($('#fullyear').text());
        nd.setMonth(parseInt($('#month').text()) - 1);
        gen(nd);
    });
    // 下个月
    $('#right').click(function () {
        var nd = new Date();
        nd.setFullYear($('#fullyear').text());
        nd.setMonth(parseInt($('#month').text()) + 1);
        gen(nd);
    });
    // 返回今日
    $('#date-title span').click(function () {
        gen(new Date());
    });
    // 隐藏
    $('#yc').click(function () {
        $('#t-nr').height(230);
        $('#template-edit-div tr.toggle-hide').hide();
        $(this).hide();
        $('#zk').show();
    });
    // 展开
    $('#zk').click(function () {
        $('#t-nr').height(70);
        $('#template-edit-div tr.toggle-hide').show();
        $(this).hide();
        $('#yc').show();
    });
    // 保存
    $('#bc').click(function () {
        if (!validForm()) return;

        $('#t-err').addClass('success').text('保存成功！').show();
        setTimeout(function () {
            $('#t-err').hide()
        }, 2000);

        var obj = {
            name: $('#t-xm option:selected').text(),
            id: $('#t-xm').val(),
            zg: $('#t-zg option:selected').text(),
            zgid: $('#t-zg').val(),
            gs: $('#t-gs').val(),
            dd: $('#t-dd').val(),
            nr: $('#t-nr').val(),
            gj: $('#t-gj').val(),
            bz: $('#t-bz').val()
        };
        window.localStorage.setItem(localVarTemplate, JSON.stringify(obj));
    });
    // 内容
    $('#t-nr').change(function () {
        var content = $(this).val(), i = 1;
        content = $.map(content.split('\n'), function (e) {
            if (e != '' && !(new RegExp('(r\d*)|(-.*)').test(e))) {
                return $.map($(e.split(/;|；/)), function (n) {
                    n = n.trim().replace(/^[0-9]*(:|：) */, '');
                    if (n != '') return i++ + ': ' + n;
                });
            }
        }).join('\r\n');
        $(this).val(content);
        $('#t-gj').val(content);
    });
    // 工时减1
    $('.sub').click(function () {
        var gs = parseFloat($('#t-gs').val());
        gs = gs.toString() === 'NaN' ? 0 : gs;
        $('#t-gs').val(gs - 1);
    });
    // 工时加1
    $('.add').click(function () {
        var gs = parseFloat($('#t-gs').val());
        gs = gs.toString() === 'NaN' ? 0 : gs;
        $('#t-gs').val(gs + 1);
    });
});

// 初始化页面数据源
function initTemplate() {
    var deptJson = window.localStorage.getItem(localVarDept);
    deptJson = deptJson == null ? [] : JSON.parse(deptJson);
    var option = '';
    $(deptJson).each(function () {
        option += '<option value="' + this.id + '">' + this.name + '</option>';
    });
    option = option == '' ? '<option>-未配置-</option>' : option;
    $('#t-xm').html(option);

    var managerJson = window.localStorage.getItem(localVarManager);
    managerJson = managerJson == null ? [] : JSON.parse(managerJson);
    option = '';
    $(managerJson).each(function () {
        option += '<option value="' + this.id + '">' + this.name + '</option>';
    });
    option = option == '' ? '<option>-未配置-</option>' : option;
    $('#t-zg').html(option);

    // 数据内容
    var dataJson = window.localStorage.getItem(localVarTemplate);
    dataJson = dataJson == null ? {} : JSON.parse(dataJson);
    if (!$.isEmptyObject(dataJson)) {
        $('#t-xm').val(dataJson.id);
        $('#t-zg').val(dataJson.zgid);
        $('#t-gs').val(dataJson.gs);
        $('#t-dd').val(dataJson.dd);
        $('#t-nr').val(dataJson.nr);
        $('#t-gj').val(dataJson.gj);
        $('#t-bz').val(dataJson.bz);
    }
}

// 生成日历
function gen(date) {
    $('.week-number').remove();

    var fullYear = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    $('#fullyear').text(date.getFullYear());
    $('#month').text(date.getMonth());

    $('#date-title span').text(fullYear + '年' + month + '月');

    // 本月第一天
    date.setDate(1);
    var firstDay = date.getDate();

    // 第一天周几
    var firstIndex = date.getDay();

    // 本月最后一天
    date.setMonth(date.getMonth() + 1, 1);
    date.setDate(date.getDate() - 1);
    var lastDay = date.getDate();

    // 最后一天周几
    var lastIndex = date.getDay();

    var rowNumber = 0;
    var html = '<div class="date-div week-number">';
    for (var i = 0; i < firstIndex; i++) {
        html += '<div></div>';
        rowNumber++;
    }
    for (var i = firstDay; i <= lastDay; i++) {
        html += '<div class="number ';
        if (i == curD.getDate() && $('#month').text() == curD.getMonth() && $('#fullyear').text() == curD.getFullYear()) {
            html += ' today';
        }
        html += '">' + i + '</div>';
        rowNumber++;
        if (rowNumber % 7 == 0 && !(i == lastDay && lastIndex == 6)) {
            html += '</div><div class="date-div week-number">';
        }
    }
    for (var i = 0; i < 6 - lastIndex; i++) {
        html += '<div></div>';
    }
    html += '</div>';

    $('#date-div').append(html);

    $('.week-number div.number').on('click', function () {
        $('.week-number div.number').removeClass('active');
        $(this).addClass('active');
        var date = $(this).text();
        if (date != '') {
            $('#selected-date').css({
                'color': '#35ca2b',
                'font-size': '14px'
            });
            var text = $('#fullyear').text() + '-' + (parseInt($('#month').text()) + 1) + '-' + date;
            $('#selected-date').text(text);
            $('#selected-date').attr('data', text);
        }
    });
}

// 验证表单
function validForm() {
    var error = true;
    $('[required]').each(function (i, e) {
        if ($(e).val() === '') {
            $(e).focus();
            error = false;
            $('#t-err').removeClass('success').text('必填项不能为空！').show();
            return false;
        }
    });
    return error;
}